<?php

namespace app\store\controller;

use app\api\model\CommissionLog;
use app\common\library\helper;
use app\common\library\wechat\WxCode;
use app\store\model\User as UserModel;
use think\db\Expression;
use think\Log;
use think\Request;
use think\Session;
use app\common\library\wechat\WxClient;
use app\store\model\Setting as SettingModel;

/**
 * 用户管理
 * Class User
 * @package app\store\controller
 */
class User extends Controller
{
    protected $notLayoutAction = [
        // 登录页面
        'agents',
        'unbind'
    ];

    public function agents($userId, $level, Request $request)
    {
        $user = \app\common\model\User::get($userId);
        $model = new UserModel;
        $filter = $this->getFilter($request);
        if ($level < 4) {
            $filter['agent_level'] = ['eq', $level - 1];
        } else {
            $filter['agent_level'] = ['lt', 4];
        }
        $filter['user_id'] = ['neq', $userId];
        $list = $model->getList($filter);
        $this->listProcess($list);
        return $this->fetch('agents', compact('list'));
    }

    private function getFilter(Request $request)
    {
        $this->assign('keyword', input('keyword'));
        $this->assign('url', $_REQUEST['s']);
        $filter = [];
        if ($level = input('level')) {
            $filter['agent_level'] = $level;
        }
        if ($keyword = $request->get("keyword")) {
            $filter['mobile|nickname'] = ['like', '%' . $keyword . '%'];
        }
        return $filter;
    }

    private function listProcess(&$list)
    {
        $agents = helper::getAgents();
        $uppers = [];
        foreach ($list as &$row) {
            if (isset($agents[$row->agent_level])) {
                $row['agentName'] = $agents[$row->agent_level]['name'];
            } else {
                $row['agentName'] = '--';
            }
            if (isset($row->upper_id) && !in_array($row->upper_id, $uppers)) {
                $uppers[] = $row->upper_id;
            }
        }
        $upperList = \app\common\model\User::where(['user_id' => ['in', $uppers]])->select();
        $upperMap = [];
        foreach ($upperList as $up) {
            if (!isset($upperMap[$up->user_id])) {
                $upperMap[$up->user_id] = $up;
            }
        }
        foreach ($list as &$row) {
            if (isset($row->upper_id) && isset($upperMap[$row->upper_id])) {
                $row['upper'] = $upperMap[$row->upper_id];
            } else {
                $row['upper'] = false;
            }
        }
    }

    /**
     * 用户列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index(Request $request)
    {
        $model = new UserModel;
        $filter = $this->getFilter($request);
        $list = $model->getList($filter);
        $this->listProcess($list);
        return $this->fetch('index', compact('list'));
    }

    /**
     * 代理的客户或者下级
     * @param $userId
     */
    public function subs($userId, Request $request)
    {
        $model = new UserModel;
        $user = $model::get($userId);
        $filter = $this->getFilter($request);
        $filter['ranking'] = ['like', $user->ranking . '%'];
        $filter['user_id'] = ['neq', $user->user_id];
        $list = $model->getList($filter);
        $this->listProcess($list);
        return $this->fetch('subs', compact('user', 'list'));
    }


    /**
     * 未绑定的下级
     * @param $userId
     * @param Request $request
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function unbind($userId, Request $request)
    {
        $model = new UserModel;
        $user = $model::get($userId);
        $filter = $this->getFilter($request);
        $filter['user_id'] = ['neq', $user->user_id];
        $filter['upper_id'] = [['EXP', new Expression("is null")], ['eq', 0], 'or'];
        $filter['agent_level'] = 4;
        $list = $model->getList($filter);
        $this->listProcess($list);
        return $this->fetch('unbind', compact('user', 'list'));
    }

    public function set_sub($userId, Request $request)
    {
        $model = new UserModel;
        $to = input('to');
        $bindUser = $model::get($userId);
        if ($bindUser->agent_level !== "4") {
            return $this->error("该用户已经成为别人的客户");
        }
        $toUser = $model::get($to);
        $bindUser->upper_id = $to;
        $bindUser->ranking = $toUser->ranking . $bindUser->ranking;
        if ($bindUser->save()) {
            return $this->success("设置成功");
        } else {
            return $this->error("设置失败");
        }
    }

    public function clear_agent($userId)
    {
        $userInfo = \app\common\model\User::get($userId);
        $userInfo->ranking = '$' . $userId;
        $userInfo->upper_id = null;
        if ($userInfo->save() !== false) {
            return $this->success("清空成功");
        } else {
            return $this->error("清空失败");
        }
    }

    public function updateShareImg()
    {
        try {
            $userId = input("userId");
            $user = \app\store\model\User::get($userId);
            $user->share_img = $user->makeShareImg();
            $user->save();
            return $this->renderSuccess("刷新成功", "", ['share_img' => $user->share_img]);
        } catch (\Exception $e) {
            return $this->renderError($e->getMessage());
        }

    }

    public function setting($userId)
    {
        if ($this->request->isPost()) {
            $input = input();
            $data = $input['user'];
            $upperId = $data['upper_id'];
            $upper = \app\common\model\User::get($upperId);
            $agentLevel = $data['agent_level'];
            if ($agentLevel == 1) $data['ranking'] = '$' . $userId;
            else {
                $upperRanking = $upper['ranking'];
                if ($upperRanking) $data['ranking'] = $upperRanking . '$' . $userId;
                else $data['ranking'] = '$' . $userId;
            }
//            if ($agentLevel < 4) {
//                $data['share_img'] = $userInfo->makeShareImg();
//            }
            \app\common\model\User::update($data, ['user_id' => $userId]);
            $this->assign('message', '设置成功！');
        }
        $user = \app\store\model\User::get($userId);
        $agents = helper::getAgents();
        krsort($agents);
        $upper = \app\store\model\User::get($user->upper_id);
        return $this->fetch('setting', compact('user', 'agents', 'upper'));
    }

    public function searchAgent($mobile)
    {
        $agents = \app\store\model\User::where(['mobile' => ['like', '%' . $mobile . '%']])->limit(0, 10)->select();
        $this->success("", "", ['agents' => $agents]);
    }

    public function sale(Request $request)
    {
        $filter = [];
        $this->assign('keyword', input('keyword'));
        $this->assign('url', $_REQUEST['s']);
        $this->assign('start_time', input('start_time'));
        $this->assign('end_time', input('end_time'));
        $filter = [];
        if ($level = input('level')) {
            $filter['u.agent_level'] = $level;
        }
        if ($keyword = $request->get("keyword")) {
            $filter['u.mobile|u.nickname'] = ['like', '%' . $keyword . '%'];
        }
        $this->getTimeFilter($filter, 'c.');
        $list = CommissionLog::alias('c')
            ->join('user u', 'u.user_id=c.user_id')
            ->where($filter)->group('c.user_id')
            ->field('sum(c.money) as total_reward,sum(c.price) as total_sale,u.*')
            ->paginate(15, false, ['query' => $request->request()]);
        $this->listProcess($list);
        return $this->fetch('sale', compact('list'));
    }

    public function sale_detail(Request $request)
    {
        $filter = [];
        $userId = input('user_id');
        $filter['c.user_id'] = $userId;
        $user = \app\common\model\User::get($userId);
        $agents = helper::getAgents();
        $user['agentName'] = $agents[$user->agent_level]['name'];
        $this->assign('url', $_REQUEST['s']);
        $this->assign('start_time', input('start_time'));
        $this->assign('end_time', input('end_time'));
        $this->getTimeFilter($filter, $request);
        $list = CommissionLog::alias('c')
            ->join('order o', 'o.order_no=c.order_no', 'left')
            ->join('user u', 'u.user_id=o.user_id', 'left')
            ->where($filter)
            ->field('c.*, u.nickName,u.avatarUrl,u.agent_level, o.pay_price, o.order_id')
            ->order("create_time desc")
            ->paginate(15, false, ['query' => $request->request()]);
        $this->listProcess($list);
        return $this->fetch('sale_detail', compact('list', 'user'));
    }


}
